import requests


# 获取当天热门视频前20个
def get_hot_list(url, headers):
    # 发送请求，获取JSON数据
    response = requests.get(url=url, headers=headers)
    return response.json()


# 解析出热门视频的标题和cid
def parse_hot_list(json_dict):
    hot_list = []
    data = json_dict['data']       # 解析出所有20个视频的详情
    for item in data['list']:      # 挨个解析
        hot_item_dict = {}
        # 解析title和cid
        title = item['title']
        cid = item['cid']
        hot_item_dict['title'] = title
        hot_item_dict['cid'] = cid
        # 构造hot_list数据结构
        hot_list.append(hot_item_dict)

    return hot_list


# 本py文件测试主函数
def main():
    # 当天热门视频前20个
    url = 'https://api.bilibili.com/x/web-interface/popular?ps=20&pn=1'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43',
        'Origin': 'https://www.bilibili.com',
        'Referer': 'https://www.bilibili.com/',
    }

    json_dict = get_hot_list(url, headers)
    hot_list = parse_hot_list(json_dict)
    print(hot_list)


# 外部调用接口
def run():
    # 当天热门视频前20个
    url = 'https://api.bilibili.com/x/web-interface/popular?ps=20&pn=1'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43',
        'Origin': 'https://www.bilibili.com',
        'Referer': 'https://www.bilibili.com/',
    }

    json_dict = get_hot_list(url, headers)
    hot_list = parse_hot_list(json_dict)
    return hot_list


if __name__ == '__main__':
    main()
